<template>
  <div class="login-container">

    <div class="title-container">
      <h3 class="title">系统登陆</h3>
    </div>

    <div class="form-container">
      <Form label-width="60px" validate-first @submit="handleLogin">
        <Field
          v-model="loginForm.username"
          autofocus
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[
            { required: true, message: '请填写用户名' },
            { validator: validateUsername, message: '请填写正确的用户名' },
          ]"
        />
        <Field
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          name="password"
          label="密码"
          placeholder="请输入密码"
          :rules="[
            { required: true, message: '请填写密码' },
            { validator: validatePassword, message: '密码最多不能超过 6 位' }
          ]"
        >
          <template slot="right-icon">
            <Icon :name="passwordType === 'password' ? 'closed-eye' : 'eye-o'" @click="showPwd" />
          </template>
        </Field>
        <div class="form-btn">
          <Button :loading="loading" loading-text="登陆中..." round block type="info" native-type="submit">登陆</Button>
        </div>
      </Form>
    </div>
  </div>
</template>

<script>
// components
import { Form, Field, Button, Icon } from 'vant'
// utils
import { validUsername } from '@/utils/validate'
// vm
export default {
  name: 'Login',
  components: {
    Form,
    Field,
    Button,
    Icon
  },
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '111111'
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    validateUsername (value) {
      return validUsername(value)
    },
    validatePassword (value) {
      return value.length >= 6
    },
    showPwd () {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin () {
      this.loading = true
      this.$store.dispatch('user/login', this.loginForm).then(() => {
        this.$router.push({ path: this.redirect || '/' })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  background-color: #283443;
}
.title-container {
  padding-top: 25%;
  padding-bottom: 15%;
  text-align: center;
  font-size: 24px;
  color: #fff;
}
.form-container {
  margin: 0 16px;
  padding: 16px;
  border-radius: 4px;
  background-color: #fff;
}
.form-btn {
  margin-top: 16px;
}
</style>
